﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IDAL;
using Model;

namespace SQLServerDAL
{

    public class UsersDAL : IUsersDAL
    {
         public Boolean InsertUser(User user) 
        {
            try
            {
                UsersDataClassesDataContext userContext = new UsersDataClassesDataContext();
                userContext.Users.InsertOnSubmit(user);
                userContext.SubmitChanges();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }


        public Boolean DeleteUser(int userId) 
        {
            try
            {
                UsersDataClassesDataContext userContext = new UsersDataClassesDataContext();
                User user = (from u in userContext.Users
                             where u.UserId.Equals(userId)
                             select u).First();
                userContext.Users.DeleteOnSubmit(user);
                userContext.SubmitChanges();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }


        public Boolean UpdateUser(int userId,User user) 
        {
            
                if (userId != user.UserId) {
                    return false;
                }
                UsersDataClassesDataContext userContext = new UsersDataClassesDataContext();
                User query = (from u in userContext.Users
                             where u.UserId.Equals(userId)
                             select u).First();
                //query.Password = user.Password;
                
                userContext.SubmitChanges();
                return true;
            
        }

        public User SelectUserById(int userId)
        {
            UsersDataClassesDataContext userContext = new UsersDataClassesDataContext();
            User user = (from u in userContext.Users
                         where u.UserId.Equals(userId)
                         select u).First();
            return user;
        }


        public List<User> SelectAllUser() 
        {
            UsersDataClassesDataContext userContext = new UsersDataClassesDataContext();
            var query = (from u in userContext.Users
                         select u);
            List<User> userList = new List<User>();

            foreach (var user in query) {
                userList.Add(user);
            }
            return userList;
        }

    }
}
